import {uSelectDevDetailByDevId, uSelectMyDevDataEcharts} from '@/api'
import {observable, computed, action} from 'mobx'
import {createContext} from 'react'
import {ParamAnalyze} from './components'

type EchartSearchData = {
  dateRange: [string, string]
}

class Singledevparams {
  @observable pageQuery: {devId: string | number | undefined} = {
    devId: undefined
  }
  @computed get getDevId() {
    return this.pageQuery.devId
  }
  @action.bound
  updatePageQuery(data: typeof this.pageQuery) {
    console.log('%c updatePageQuery', 'color:green')
    this.pageQuery = data
  }

  @observable echartSearchData: EchartSearchData = {
    dateRange: ['', '']
  }
  @computed get echartDateRange() {
    let s = this.echartSearchData.dateRange[0]
      ? this.echartSearchData.dateRange[0] + ' 00:00:00'
      : ''
    let e = this.echartSearchData.dateRange[1]
      ? this.echartSearchData.dateRange[1] + ' 23:59:59'
      : ''
    return [s, e]
  }

  @action.bound
  updateEchartSearchData(data: {
    [key in keyof EchartSearchData]?: EchartSearchData[key]
  }) {
    Object.assign(this.echartSearchData, data)
  }
  @action.bound
  updateDateRange(data: [string, string]) {
    this.echartSearchData.dateRange = data
    this.updateDevAnalyze()
  }

  @observable devDetil: Device.DevDetailData | null = null
  @action.bound
  updateDevDetil(userId: string | number) {
    if (!this.pageQuery.devId) return
    uSelectDevDetailByDevId({
      devId: this.pageQuery.devId,
      userId
    })
      .then(res => {
        this.devDetil = res.data
      })
      .catch(err => {
        this.devDetil = null
      })
  }

  @observable devAnalyze: ParamAnalyze | null = null
  @action.bound
  updateDevAnalyze() {
    if (!this.pageQuery.devId) return
    uSelectMyDevDataEcharts({
      devId: this.pageQuery.devId,
      startDate: this.echartDateRange[0],
      endDate: this.echartDateRange[1]
    })
      .then(res => {
        this.devAnalyze = res.data
      })
      .catch(err => {
        this.devAnalyze = null
      })
  }

  @action.bound
  clearPage() {
    this.pageQuery = {devId: undefined}
    this.echartSearchData = {dateRange: ['', '']}
    this.devAnalyze = null
    this.devDetil = null
  }
}
export const singledevparamsStore = createContext(new Singledevparams())
export default Singledevparams
